package com.example.myimageshare.View;

import androidx.annotation.NonNull;
import androidx.annotation.PluralsRes;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.customview.widget.ViewDragHelper;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.myimageshare.Utils.LoginUtil;
import com.example.myimageshare.Utils.MyTextUtil;
import com.example.myimageshare.adapter.DeleteAdapter;
import com.example.myimageshare.adapter.ImageListAdapter;
import com.example.myimageshare.domain.User;
import com.example.myimageshare.R;
import com.example.myimageshare.domain.UserArt;
import com.example.myimageshare.entity.PhotoItem;
import com.example.myimageshare.entity.UserArtItem;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

import java.lang.reflect.Field;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, DeleteFragment.OnFragmentInteractionListener {

    public static final String TAG = MainActivity.class.getSimpleName(); //日志

//  初始化组件
    private Toolbar toolbar;
    private FloatingActionButton fab_home;
    private TextView tv_select_count_delete;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;

    private NavigationView nView;
    private View headerLayout;
    private ImageView iv_nv_user_head;

    private TextView tv_nickname;
    private TextView tv_signature;


//  Framement控制相关
    FragmentTransaction fragmentTransaction;
    FragmentManager manager;
    Fragment fl,fragment_1,fragment_2,fragment_3,fragment_upload;

    //Layout控制相关

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Bmob默认初始化
        Bmob.initialize(this,getString(R.string.appKey));
//        BmobUser.logOut();



        initView();
        initData();
        initListener();
//        System.out.println("活动得到数据:"+user_Info.get(0).getUserName());
        //获取管理
        manager = getSupportFragmentManager();
        //实例化fragment
        fragment_1 = new HomeFragment(this);
        fragment_2 = new DeleteFragment();
        fragment_3 = new ImageFragment();
        fragment_upload = new UploadFragment();



        //打开返回键监听
        mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,
                toolbar, R.string.open, R.string.close){
            @Override
            public void onDrawerOpened(View drawerView){
                super.onDrawerOpened(drawerView);
                fab_home.setVisibility(View.GONE);
            }
            @Override
            public void onDrawerClosed(View drawerView){
                super.onDrawerClosed(drawerView);
                fab_home.setVisibility(View.VISIBLE);
            }
        };
        setDrawerLeftEdgeSize(this,mDrawerLayout,1);
        mDrawerToggle.syncState();
        //setDrawerListener弃用
        mDrawerLayout.addDrawerListener(mDrawerToggle);


        //状态栏沉浸
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){

            WindowManager.LayoutParams barLayoutParams=getWindow()
                    .getAttributes();
            barLayoutParams.flags=(WindowManager
                    .LayoutParams.FLAG_TRANSLUCENT_STATUS|barLayoutParams.flags);

        }
        initLocalUserData();
        //设置适配器
        //默认打开第一个页面
        selectFragment(0);

    }
    /*全屏滑动
    * */
    private void setDrawerLeftEdgeSize (Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) {
        if (activity == null || drawerLayout == null) return;
        try {
            // 找到 ViewDragHelper 并设置 Accessible 为true
            Field leftDraggerField =
                    drawerLayout.getClass().getDeclaredField("mLeftDragger");//Right
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);

            // 找到 edgeSizeField 并设置 Accessible 为true
            Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);

            // 设置新的边缘大小
            Point displaySize = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
            edgeSizeField.setInt(leftDragger, Math.max(edgeSize, (int) (displaySize.x *
                    displayWidthPercentage)));
        } catch (NoSuchFieldException e) {
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        }
    }

    /*页面选择
     * */
    private void selectFragment(int index){
        //开启Fragment事务
        FragmentTransaction transaction = manager.beginTransaction();
        fragmentTransaction = transaction;
//        隐藏上次的Fragment
        hideFragment(transaction);
        switch (index){
            case 0:
                //为空添加
                if(!fragment_1.isAdded()){
                    //实例化
                    fragment_1 = new HomeFragment(this);
                    //添加
                    transaction.add(R.id.Container_content,fragment_1);
                }else {
                    //不为空显示
                    transaction.show(fragment_1);
                }
                break;
            case 1:
                if(!fragment_2.isAdded()){
                    fragment_2 = new DeleteFragment();
                    transaction.add(R.id.Container_content,fragment_2);
                }else {
                    transaction.show(fragment_2);
                }
                break;
            case 2:
                if(!fragment_3.isAdded()){
                    fragment_3 = new ImageFragment();
                    transaction.add(R.id.Container_content,fragment_3);
                }else {
                    transaction.show(fragment_3);
                }
                break;
            case 3:
                if(!fragment_upload.isAdded()){
                    fragment_upload = new UploadFragment();
                    transaction.add(R.id.Container_content,fragment_upload);
                }else {
                    transaction.show(fragment_upload);
                }
                break;
        }
        //提交事务
        transaction.commit();

    }

    public void initView(){
        //绑定控件
        toolbar = findViewById(R.id.tl_custom);
        fab_home = findViewById(R.id.fab_home);
        tv_select_count_delete = findViewById(R.id.select_count_delete);
        tv_select_count_delete.setVisibility(View.GONE);
        mDrawerLayout = findViewById(R.id.dl_left);
        //获取侧滑菜单的头部
        nView = findViewById(R.id.nav_view);
        headerLayout = nView.inflateHeaderView(R.layout.nav_head);
        iv_nv_user_head = headerLayout.findViewById(R.id.iv_head_imageView);
        tv_nickname = headerLayout.findViewById(R.id.tv_head_nickname);
        tv_signature = headerLayout.findViewById(R.id.tv_head_signature);

        //设置ToolBar标题及颜色
        toolbar.setTitleTextColor(Color.BLACK);
        toolbar.setTitle("主页");
        setSupportActionBar(toolbar);
        //设置返回键
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    public void initData(){
        nView.setNavigationItemSelectedListener(this);
    }

    private void initLocalUserData(){


        User userLoad = BmobUser.getCurrentUser(User.class);
        Log.d(TAG, "用户名为：" + userLoad.isLogin());
        if(userLoad.isLogin()!=false) {
            Log.d(TAG, "用户名为：" + userLoad.getUsername());

            Log.d(TAG, "用户昵称为：" + userLoad.getNickname());
            tv_nickname.setText(userLoad.getNickname());
            Log.d(TAG, "用户个性签名为：" + MyTextUtil.Cut(userLoad.getSignature()));
            tv_signature.setText(userLoad.getSignature());

            Log.d(TAG, "用户头像URL为：" + userLoad.getHeadimg());

            Glide.with(this).clear(iv_nv_user_head);
            Glide.with(this)
                    .load(userLoad.getHeadimg())
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(iv_nv_user_head);
        }

    }

/*打开相关触发事件*/
    public void initListener(){
        //侧边栏头像点击事件
        iv_nv_user_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(LoginUtil.getUserStatus().isLogin()) {
                    Intent intent = new Intent(MainActivity.this,
                            UserInfoActivity.class);
                    startActivity(intent);
                }else {
                    login();
                    Log.d(TAG,"登录成功");
                    initLocalUserData();
                }
            }
        });

        //显示主页事件
        fab_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectFragment(0);
                toolbar.setTitle("主页");
            }
        });

    }

    private void login(){
        User userCheck = BmobUser.getCurrentUser(User.class);
        Log.d(TAG,""+userCheck.isLogin());
        if(userCheck.isLogin()==false) {
            Log.d(TAG,"开始登录");
            Intent loginIntent = new Intent(this,LoginActivity.class);
            startActivityForResult(loginIntent,0);
        }
    }

    /*注销登录*/
    private void logout(){
        BmobUser.logOut();
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        initLocalUserData();
    }



        /*DeleteFragment
    * 接口实现1*/
    @Override
    public void onFragmentInteraction(String s) {

        switch (s){
            case "show_tv_delete":
                tv_select_count_delete.setVisibility(View.VISIBLE);
                Log.d(TAG,"显示删除按钮");
                break;
            case "hide_tv_delete":
                tv_select_count_delete.setVisibility(View.GONE);
                Log.d(TAG,"隐藏删除按钮");
                break;
        }
    }

    /*DeleteFragment
     * 接口实现2*/
    @Override
    public void onFragmentInteraction(UserArtItem item) {
        tv_select_count_delete.setEnabled(item.isEnable());
        tv_select_count_delete.setText(item.getText());
        tv_select_count_delete.setTextColor(item.getTextColor());
    }

    @Override
    public void OnFabConfirm(int imgs) {
        Toast.makeText(this,
                "成功删除"+imgs+"条",Toast.LENGTH_SHORT).show();
    }

    /*单一栈模式*/
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //在这里处理intent传回来的数据
        initLocalUserData();
    }

    /*隐藏非空Fragment
    * */
    private void hideFragment(FragmentTransaction transaction){
        if(fragment_1 != null){
            transaction.hide(fragment_1);
        }
        if (fragment_2 != null) {
            transaction.hide(fragment_2);
        }
        if (fragment_3 != null) {
            transaction.hide(fragment_3);
        }
        if(fragment_upload !=null ){
            transaction.hide(fragment_upload);
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        String str = item.getTitle().toString();
        System.out.println(str);
        Toast.makeText(MainActivity.this,str,
                Toast.LENGTH_SHORT).show();
        //页面选择
        switch (item.getItemId()){

            case R.id.nav_upload:
//                selectFragment(0);
                //假设得到用户登录登录信息，taken
                if(LoginUtil.getUserStatus().isLogin()) {
                    selectFragment(3);
                    toolbar.setTitle("上传作品");
                }else {
                    login();
                    initLocalUserData();
                }
                break;
            case R.id.nav_clean:
                if(LoginUtil.getUserStatus().isLogin()) {
                    selectFragment(1);
                    toolbar.setTitle("清理作品");
                }else {
                    login();
                    initLocalUserData();
                }
                break;
            case R.id.nav_mark:
                if(LoginUtil.getUserStatus().isLogin()) {
                    selectFragment(2);
                    toolbar.setTitle("我的关注");
                }else {
                    login();
                    initLocalUserData();
                }
                break;
            case R.id.nav_logout:
                if(LoginUtil.getUserStatus().isLogin()) {
                    logout();
                    initLocalUserData();
                }else {
                    Toast.makeText(MainActivity.this,
                            "请注册一个账号",Toast.LENGTH_SHORT);
                    login();
                    initLocalUserData();
                }
            case R.id.nav_account:
                if(LoginUtil.getUserStatus().isLogin()) {
                    Intent intent = new Intent(MainActivity.this,
                            PasswordActivity.class);
                    startActivity(intent);
                    initLocalUserData();
                }else {
                    Toast.makeText(MainActivity.this,
                            "请登录",Toast.LENGTH_SHORT);
                    login();
                    initLocalUserData();
                }
            default:
                break;
        }
        mDrawerLayout.closeDrawers();
        return true;
    }

}
